package com.huluobo.mvvmdemo2006a.adapter;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.DiffUtil;
import androidx.recyclerview.widget.ListAdapter;
import androidx.recyclerview.widget.RecyclerView;

import com.huluobo.mvvmdemo2006a.databinding.ItemCartBinding;
import com.huluobo.mvvmdemo2006a.model.CartItem;

/**
 * Created by lc on 2023/1/9.
 */
public class CartListAdapter extends ListAdapter<CartItem, CartListAdapter.CartViewHolder> {

    private CartInterface cartInterface;

    public CartListAdapter(CartInterface cartInterface) {
        super(CartItem.itemItemCallback);
        this.cartInterface = cartInterface;
    }

    @Override
    public CartViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        LayoutInflater layoutInflater = LayoutInflater.from(parent.getContext());
        ItemCartBinding itemCartBinding = ItemCartBinding.inflate(layoutInflater, parent, false);
        return new CartViewHolder(itemCartBinding);
    }

    @Override
    public void onBindViewHolder(@NonNull CartListAdapter.CartViewHolder holder, int position) {
        holder.itemCartBinding.setCartItem(getItem(position));

        //强制执行页面刷新,局部刷新
        holder.itemCartBinding.executePendingBindings();
    }

    class CartViewHolder extends RecyclerView.ViewHolder {

        ItemCartBinding itemCartBinding;

        public CartViewHolder(@NonNull ItemCartBinding itemCartBinding) {
            super(itemCartBinding.getRoot());
            this.itemCartBinding = itemCartBinding;

            itemCartBinding.deleteCartItem.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    cartInterface.deleteCartItem(getItem(getAdapterPosition()));
                }
            });

            itemCartBinding.quantitySpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
                @Override
                public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                    int quantity = position + 1;//因为选择的是下标,所以需要进行+1操作
                    if (quantity != getItem(getAdapterPosition()).getQuantity()) {//如果选择数量和之前的数量一致,则不做操作
                        cartInterface.changeQuantity(getItem(getAdapterPosition()), quantity);
                    }
                }

                @Override
                public void onNothingSelected(AdapterView<?> parent) {

                }
            });
        }
    }

    public interface CartInterface {
        void deleteCartItem(CartItem cartItem);

        void changeQuantity(CartItem cartItem, int quantity);
    }
}
